import time

import uiautomator2 as u2
import traceback
from game import (game_山海北荒卷, game_我就爱消除, game_几何王国, zz_game, game_仙剑奇侠传, game_冒险大作战, game_寻道大千, game_小鸟爱飞翔
, game_叫我大掌柜, game_欢乐消消消, game_跃动小子, game_灵剑仙师, game_灵魂序章, game_小鸡舰队出击, game_动物餐厅, game_猎场HD, game_约战沙城, game_金币大富翁
, game_卓越传说, game_这城有良田, game_修道, game_乌冬的旅店, game_疯狂接化发, game_天剑奇缘, game_王牌探险家, game_无名之辈, game_傲视苍穹, game_青云诀之伏魔
, game_秘钥开箱, game_暴走弹头, game_王牌机战, game_植物大战僵尸, game_九梦仙域, game_向僵尸开炮, game_小小英雄, game_次神光之觉醒, game_塔防精灵, game_超级逗萌兽
, game_大圣顶住, game_茶叶蛋大冒险, game_行侠仗义五千年, game_宫爆老奶奶, game_武侠大明星)
from game import game_淘宝农场_砸蛋, game_淘宝农场_鸡场, game_淘宝农场_健康岛, game_福气

from zz import zz_return, zz_log, zz_code, zz_dingtalk, zz_str

log = zz_log.of()

d = None
try:
    d = u2.connect(zz_code.env('DEVICE_ID'))
except Exception as ex:
    errmsg = str(ex)
    log.error(errmsg)
    # if zz_str.contains(errmsg, 'not online'):
    zz_dingtalk.send_markdown(errmsg, 'phone not online')

baba_game = game_几何王国.Game(d, 30)


def get_task(d):
    return {
        # '乌冬的旅店': game_乌冬的旅店.Game(d),
        '九梦仙域': game_九梦仙域.Game(d),
        '仙剑奇侠传之新的开始': game_仙剑奇侠传.Game(d),
        # '修道': game_修道.Game(d),
        # '傲视苍穹': game_傲视苍穹.Game(d, False),
        '冒险大作战': game_冒险大作战.Game(d),
        # '几何王国': game_几何王国.Game(d, 3),
        # '动物餐厅': game_动物餐厅.Game(d),
        # '卓越传说': game_卓越传说.Game(d),
        # '叫我大掌柜': game_叫我大掌柜.Game(d, False),
        '向僵尸开炮': game_向僵尸开炮.Game(d),
        # '塔防精灵': game_塔防精灵.Game(d),
        # '大圣顶住': game_大圣顶住.Game(d),
        # '天剑奇缘': game_天剑奇缘.Game(d),
        # '宫爆老奶奶': game_宫爆老奶奶.Game(d),
        # '寻道大千': game_寻道大千.Game(d),
        # '小小英雄': game_小小英雄.Game(d),
        # '小鸟爱飞翔': game_小鸟爱飞翔.Game(d, False),
        '小鸡舰队出击': game_小鸡舰队出击.Game(d),
        # '山海北荒卷': game_山海北荒卷.Game(d),
        # '我就爱消除': game_我就爱消除.Game(d),
        # '无名之辈': game_无名之辈.Game(d),
        # '暴走弹头': game_暴走弹头.Game(d),
        #'植物大战僵尸': game_植物大战僵尸.Game(d),
        # '次神光之觉醒': game_次神光之觉醒.Game(d),
        # '欢乐消消消': game_欢乐消消消.Game(d),
        '武侠大明星': game_武侠大明星.Game(d),
        # '灵剑仙师': game_灵剑仙师.Game(d, True),
        '灵魂序章': game_灵魂序章.Game(d),
        # '猎场HD': game_猎场HD.Game(d, False),
        # '王牌探险家': game_王牌探险家.Game(d, False),
        # '王牌机战': game_王牌机战.Game(d),
        # '疯狂接化发': game_疯狂接化发.Game(d),
        # '秘钥开箱': game_秘钥开箱.Game(d),
        # '约战沙城': game_约战沙城.Game(d),
        # '茶叶蛋大冒险': game_茶叶蛋大冒险.Game(d),
        # '行侠仗义五千年': game_行侠仗义五千年.Game(d),
        # '超级逗萌兽': game_超级逗萌兽.Game(d),
        # '跃动小子': game_跃动小子.Game(d),
        # '金币大富翁': game_金币大富翁.Game(d),
        # '青云诀之伏魔': game_青云诀之伏魔.Game(d),
    }


def main_before():
    if d is None:
        return

    g = zz_game.ZZ_Game(d)

    try:
        main(d)

        # 切换帐号
        r_ca = zz_game.change_account(g)
        if r_ca.ok():
            g.log_msg('切换成功')
            main_before()  # 重新运行
            return
        g.log_msg('已完成所有帐号任务')

    except Exception as ex:
        traceback.print_exc()
        # 报错重新运行
        time.sleep(2)
        main_before()


def main(d: u2.Device):
    # d = u2.connect("adb-ANGYVB4311002483-g5bqTE._adb-tls-connect._tcp")  # 荣耀100
    # d = u2.connect(zz_code.env('DEVICE_ID'))
    d.debug = False
    d.implicitly_wait(5)
    g = zz_game.ZZ_Game(d)

    g.open_app()
    # 记录开始时间
    g.set_begin_time()
    #
    game_淘宝农场_砸蛋.Game(d).handle_main()
    d.sleep(1)
    # game_淘宝农场_鸡场.Game(d).handle_main()
    # d.sleep(1)
    game_淘宝农场_健康岛.Game(d).handle_main()
    d.sleep(1)

    # # 顶住先
    zz_game.config_set('__account_done', 1)
    return

    if not g.open_game_center():
        return

    # log.info("已进入游戏中心主页")
    # g.swipe_down()
    # g.swipe_down()
    # g.qian()
    # game_福气.Game(d).handle_main()
    # d.sleep(1)

    task_items = get_task(d)
    handle_game_all(d, task_items)
    # handle_game_all(d, task_items, True)

    dou_sum = g.get_dou_sum()
    zz_game.config_set('__dou', dou_sum)  # 记录获取豆数量
    dou_sum_total = zz_game.config_get('__dou_total')  # 记录获取豆数量
    g.get_dou()  # 领乐豆
    zz_game.config_set('__account_done', 1)
    g.close_game()  # 回到主页

    send_msg = zz_game.config_get('__send_msg')
    if send_msg == 1:
        g.log_msg("消息已发过")
        return
    zz_game.config_set('__send_msg', 1)

    time_end = zz_code.date_now()
    r = zz_game.config_to_return()
    time_begin = zz_code.date_from_str(r.get_data("__begin_time"))
    time_duration = time_end - time_begin

    r = zz_game.config_to_return(True)
    account_id = r.get_data('__account_id')
    # 发送通知
    game_dict = zz_game.r_to_dict(r)
    game_count = len(game_dict)  # 游戏总数
    game_count_ok = 0  # 游戏成功-总数
    game_items = game_dict.items()
    for k, v in game_items:
        if v['state']:
            game_count_ok += 1
    title = f"game: {game_count_ok}/{game_count}, 欢乐豆: ({dou_sum})[{dou_sum_total}]"
    account = zz_game.config_path.split('_')[-1]
    msg = f"{account} \n\n {account_id} \n\n **{title}** \n\n 运行时长：{round(time_duration.seconds / 60, 1)}分钟 \n\n"
    #
    top_x = 10
    msg += f"**耗时最长的{top_x}个游戏** \n\n"
    game_items_top3 = sorted(game_items, key=lambda item: item[1]['handle_second'], reverse=True)[:top_x]
    for key, item in game_items_top3:
        msg += f"{key}：{round(item['handle_second'] / 60, 1)}分钟 \n\n"

    msg += f"**运行失败的游戏** \n\n"
    for key, item in game_items:
        if item['state']:
            continue
        msg += f"{key}\n\n"
    zz_dingtalk.send_markdown(msg, title)


def handle_game_all(d: u2.Device, task_items: dict, rehandle: bool = False):
    """
    运行所有游戏
    :param rehandle: true:处理失败，重新运行
    """
    if rehandle:
        log.info("查找运行失败的游戏，再尝试1次")
    else:
        log.info("查找未完成的游戏")

    g = zz_game.ZZ_Game(d)
    task_items_not_run = []
    r = zz_game.config_to_return()
    for item in task_items:
        if r.exists(item):
            game_handle = task_items[item]
            if game_handle.play_only_1():
                # 游戏标记只运行1次
                continue

            game_data = r.get_data(item)
            if game_data['state'] is not None:
                if not rehandle:
                    # 非第2次运行
                    continue
                if game_data['state'] is True:
                    continue
                if game_data['err_count'] > 1:
                    # 失败超过2次，pass
                    continue

        task_items_not_run.append(item)

    if len(task_items_not_run) <= 0:
        log.info("游戏已全部运行完成")
        log.info("点击玩游戏")
        g.img_click("./game/img/play_game00.png")
    else:
        if rehandle:
            log.info(f"运行失败的游戏：{len(task_items_not_run)} / {len(task_items)}")
        else:
            log.info(f"未完成的游戏：{len(task_items_not_run)} / {len(task_items)}")
        # log.info("点击玩游戏")
        # g.img_click("./game/img/play_game00.png")
        # log.info("点击前行搜索")
        # g.img_click("./game/img/search.png", 3)
        # log.info("点击搜索框")
        # d.xpath('//android.view.View[@text="搜索框"]').click()
        # g.img_click("./game/img/play_game00.png")
        g.img_click_if_exists('点击游戏圈', "./game/img/game_center_quan_btn.png", "./game/img/game_center_index01.png")
        g.log_msg("点击搜索游戏")
        g.img_click("./game/img/game_center_quan_search.png")

        for game_name in task_items_not_run:
            g.log_msg("搜索清空输入框")
            d(className='android.widget.EditText').clear_text()
            d.sleep(2)
            log.info(f"搜索游戏-{game_name}")
            d.xpath('//android.widget.EditText').set_text(game_name)
            d.sleep(1)
            g.log_msg("点击搜索")
            d.xpath('//android.widget.TextView[@text="搜索"]').click()
            d.sleep(2)
            gg = task_items[game_name]
            gg.img_click_for(f'点击秒玩[{gg.search_click_index()}]', "./game/img/search_go.png", gg.search_click_index())
            # d.xpath('//android.widget.Button[@text="秒玩"]').all()[0].click()
            # print(gg)

            # gg.log_msg("等10秒")
            # gg.d.sleep(10)
            # gg.close_game()  # 退出游戏
            # while not gg.d.xpath('//*[@text="游戏中心"]').wait(2):
            #     gg.log_msg("退出游戏失败，再退出")
            #     gg.close_game(not gg.play_only_1())  # 退出游戏
            # gg.d.sleep(2)
            # gg.log_msg("点击返回")
            # gg.d.press("back")
            # while not gg.img_exit("./game/img/game_center_index01.png", 3):
            #     gg.log_msg("点击返回失败，再返回")
            #     gg.d.press("back")
            # gg.log_msg(f"从玩游戏福豆页面进入，{game_name}")
            # gg.img_click("./game/img/play_game00.png")
            # gg.xpath_click(f'//android.widget.TextView[@text="{game_name}"]')

            gg.handle()
            d.sleep(2)

        g.log_msg("游戏全部完成")
        g.log_msg("点击返回")
        g.d.press("back")


if __name__ == '__main__':
    main_before()
